package dk.kapetanovic.jaft.action;


import java.io.File;
import java.io.IOException;

import dk.kapetanovic.jaft.action.io.FileHandler;
import dk.kapetanovic.jaft.transaction.Transaction;

public abstract class OpenFileAction implements Action {
	
	protected File original;
	private boolean exists;
	private File backup;
	private boolean delete;
	private transient Transaction transaction;
	private FileHandler handler;
	
	public OpenFileAction(File original, boolean deleteOriginal, Transaction transaction) {
		this.original = original;
		this.delete = deleteOriginal;
		this.exists = original.exists();
		handler = new FileHandler();
		setTransaction(transaction);
	}

	@Override
	public void cleanup() throws IOException {
		if(backup != null && backup.exists())
			handler.delete(backup);
	}

	@Override
	public Transaction getTransaction() {
		return transaction;
	}

	@Override
	public void prepare() throws IOException {
		if(exists) {
			backup = handler.generateBackup(original);
			if(backup.exists())
				throw new IOException("Backup file exists: " + backup.getAbsolutePath());
			
			if(delete)
				handler.rename(original, backup);
			else
				handler.copy(original, backup);
		}
	}

	@Override
	public void setTransaction(Transaction transaction) {
		this.transaction = transaction;
		handler.setBackupDir(transaction.
			getTransactionManager().getBackupDir());
	}

	@Override
	public void undo() throws IOException {
		if(exists)
			handler.restoreBackup(original, backup);
		else
			if(original.exists())
				handler.delete(original);
	}
	
	@Override
	public String toString() {
		return "OpenFileAction [original=" + original + ", backup=" + backup + 
			", deleteOriginal=" + delete + "]";
	}
}
